package com.crawler.waf.security.authentication.mac;

import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.security.sasl.AuthenticationException;
import javax.servlet.http.HttpServletRequest;

import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.crawler.waf.exceptions.extendExceptions.UcAuthenticationException;
import com.crawler.waf.exceptions.messages.ErrorMessage;
import com.crawler.waf.security.authentication.PreAuthenticatedAuthenticationExtractor;
import com.crawler.waf.utils.StringUtil;

@Component
@Order(20)
public class PreAuthenticatedMacTokenAuthenticationExtractor implements PreAuthenticatedAuthenticationExtractor {
	
	public PreAuthenticatedMacTokenAuthenticationExtractor(){
		//TODO
	}
	
    @Override
    public String getPrefix() {
        return "MAC";
    }

    @Override
    public Authentication extractAuthentication(String authenticationValue, HttpServletRequest request) throws AuthenticationException {		
    	String host = request.getHeader("Host");
		if (StringUtils.isEmpty(host)) {
			try {
				host = InetAddress.getLocalHost().getHostAddress();
			} catch (UnknownHostException e) {
				e.printStackTrace();
				 ErrorMessage em = new ErrorMessage();
				 em.setCode("WAF/AUTHEN_HOST_MISSING");
				 em.setMessage("the host is null!");
                 throw new UcAuthenticationException(em, HttpStatus.PAYMENT_REQUIRED);
			}
		}
		String requestURI = StringUtil.urlHandler(request);
		requestURI = StringUtil.getURI(host, request.getServerPort(), requestURI);
		
		String[] tokenSlips = authenticationValue.split(",");
        if(tokenSlips.length<3){
        	throw new InsufficientAuthenticationException(null);
        }
		String id = tokenSlips[0].substring(tokenSlips[0].indexOf("=") + 1).replace("\"", "").trim();
		String nonce = tokenSlips[1].substring(tokenSlips[1].indexOf("=") + 1).replace("\"", "").trim();
		String mac = tokenSlips[2].substring(tokenSlips[2].indexOf("=") + 1).replace("\"", "").trim();
		return new PreAuthenticatedMacTokenAuthentication(id,mac,nonce,request.getMethod(),requestURI, host);
    }
}
